const jsonwebtoken = require('jsonwebtoken')
const {fromBase64, toBase64} = require("js-base64");
const resultFormatMiddleware = require("./resultFormat.Middleware");

class TokenMiddleware {
    constructor() {

    }

    sign = payload => toBase64(jsonwebtoken.sign(payload, '123456', {algorithm: 'HS256', expiresIn: 60 * 60}))

    verify = (token, key = '123456') => jsonwebtoken.verify(fromBase64(token), key, {algorithms: ['HS256', 'RS256']})

    verifyMiddleware(req, res, next) {
        let {token} = req.headers
        if (!token) return resultFormatMiddleware.fail(res, 'please add token on headers', 500, [])

        try {
            req.user = new TokenMiddleware().verify(token)
            // req.user ? delete req.user.password : void 0
            next()
        } catch (e) {
            return resultFormatMiddleware.fail(res, e.message, 500, [])
        }

    }
}

module.exports = new TokenMiddleware()
